const express = require('express')
const router = express.Router()
const db = require('../db')
const consts = require('../../consts/Consts')

/**
 * @api {get} http://127.0.0.1:3658/user/all web获取所有用户
 * @apiDescription web获取所有用户
 * @apiName all
 * @apiGroup web用户接口
 *
 * @apiSuccess {int} code 状态码.
 * @apiSuccess {String} data  json数据.
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 20000,
 *      "result" : {}
 *
 *  }
 * @apiVersion 1.0.0
 */
router.get('/all', (req, res, err) => {
  console.log('---api: /all: ')
  db.UserDb.all((err, users) => {
    if (err) throw err
    res.send({
      code: 20000,
      data: users
    })
  })
})

router.get('/page', (req, res, err) => {
  console.log('---user: /page: ')
  db.UserDb.page((err, users) => {
    if (err) throw err
    console.log(users)
    res.send(users)
  })
})
/**
 * @api {post} http://127.0.0.1:3658/user/add web添加用户
 * @apiDescription web添加用户
 * @apiName add
 * @apiGroup web用户接口
 * @apiParam (body) {String} phone 手机号
 * @apiParam (body) {String} name 名字
 *
 * @apiSuccess {int} code 状态码.
 * @apiSuccess {String} result  json数据.
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 20000,
 *      "data" : {}
 *
 *  }
 * @apiVersion 1.0.0
 */
router.post('/add', (req, res, next) => {
  console.log('/user/add')
  const phone = req.body.phone
  const name = req.body.name
  console.log('tel: ' + phone + ' name: ' + name)
  db.UserDb.insert(
    {phoneNumber: phone, pwd: '123456', name: name},
    (err, raw) => {
      if (err) {
        console.log(err)
        if (err.errno === 19) {
          res.send({
            code: consts.RES_OK,
            data: 'RES_SQLITE_CONSTRAINT'
          })
        } else {
          res.end()
        }
      } else {
        res.send({
          code: consts.RES_OK,
          data: 'ok'
        })
      }
    }
  )
})
/**
 * @api {post} http://127.0.0.1:3658/user/del web删除用户
 * @apiDescription web删除用户
 * @apiName del
 * @apiGroup web用户接口
 * @apiParam (body) {String} phoneNumber 手机号
 *
 * @apiSuccess {int} code 状态码.
 * @apiSuccess {String} data  json数据.
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 20000,
 *      "data" : {}
 *
 *  }
 * @apiVersion 1.0.0
 */
router.get('/del', (req, res) => {
  const phoneNumber = req.query.phoneNumber
  db.UserDb.delete(phoneNumber, (err, row) => {
    if (err) throw err
    res.send({
      code: 20000,
      data: phoneNumber
    })
  })
})

module.exports = router
